import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
    Card, Row, Col, Select, Button, Modal,
} from 'antd';

import { addTab } from '@/utils/utils';

import { DetailInfoItem } from '../data';
import CabImages from './CabImages';

const { Option } = Select;

interface CabinetInfoProps {
    dispatch?: Dispatch;
    detailInfo?: DetailInfoItem;
    slaveTypeList?: any[];
    forms: any;
    hardwareVersion: string;
    changeLayout: (value: number, type: number) => void;
    getAllChars: () => void;
    fetchAction: (typeName: string, payload?: any) => void;
    layoutInfo: any[];
}

interface CabinetInfoState {
    is_data: boolean;
    vice_cabinet_list: any[];
    delVisible: boolean;
    deleteInfo: {
        id: number;
        slaveCode: string;
    };
    mainCellVisbile: boolean;
    showImg: any;
}

@connect(({
    cabinetManagementAdd: { detailInfo, slaveTypeList },
}: any) => ({ detailInfo, slaveTypeList }))

class CabinetInfoElem extends Component<CabinetInfoProps, CabinetInfoState> {
    state = {
        is_data: false,
        vice_cabinet_list: [],
        delVisible: false,
        deleteInfo: {
            id: 0,
            slaveCode: '',
        },
        mainCellVisbile: false,
        showImg: {
            src: 1,
            title: '示例图',
        },
    }

    static getDerivedStateFromProps(nextProps: CabinetInfoProps, preState: CabinetInfoState) {
        const {
            detailInfo,
            slaveTypeList = [],
            layoutInfo,
            hardwareVersion,
        }: any = nextProps;
        const { is_data } = preState;
        if (detailInfo.cellInfo && detailInfo.cellInfo.length > 0 && !is_data) {
            return ({
                is_data: true,
                vice_cabinet_list: detailInfo.cellInfo,
            });
        }
        const is_version = hardwareVersion !== '5.0' && hardwareVersion !== '6.0' && hardwareVersion !== '7.0';
        if (!detailInfo.id && is_version) {
            return {
                showImg: slaveTypeList[0] ? {
                    src: slaveTypeList[0].key,
                    title: slaveTypeList[0].value,
                } : { key: '1', title: '示例图' },
            };
        }
        if (!detailInfo.cellInfo) {
            const { vice_cabinet_list: A } = preState;
            if (!detailInfo.id) {
                return ({
                    vice_cabinet_list: [...layoutInfo],
                });
            }
            return ({
                vice_cabinet_list: [...layoutInfo, ...A],
            });
        }
        return null;
    }

    handlechangeLayout = (value: any, type: number) => { // 改变副柜布局
        const { changeLayout } = this.props;
        changeLayout(value, type);
    }

    handleAddVice = () => {
        const { vice_cabinet_list }: any = this.state;
        const { getAllChars }: any = this.props;
        const allChars = getAllChars();
        const { length } = vice_cabinet_list;

        const lastChar = length > 0
            ? vice_cabinet_list[length - 1].slaveCode : 'A';
        const index = allChars.indexOf(lastChar);
        const addVice = {
            isAdd: 1,
            slaveCode: allChars[length > 0 ? index + 1 : index],
            slaveType: 1,
        };
        const vice_list = [
            ...vice_cabinet_list,
            addVice,
        ];

        this.setState({
            vice_cabinet_list: [...vice_list],
        });
    }

    handleShowDelModal = (delVisible: boolean, row: any = {}) => {
        const { vice_cabinet_list } = this.state;
        const new_vice_list = JSON.parse(JSON.stringify(vice_cabinet_list));
        const isAdd = row ? row.isAdd : '';
        if (isAdd) {
            new_vice_list.splice(vice_cabinet_list.length - 1, 1);
            this.setState({
                vice_cabinet_list: new_vice_list,
            });
        } else {
            const { detailInfo: { id } }: any = this.props;
            const deleteInfo = {
                id,
                slaveCode: row.slaveCode,
            };
            this.setState({ delVisible, deleteInfo });
        }
    }

    handleDelSubmit = () => {
        const { deleteInfo } = this.state;
        const { fetchAction }: any = this.props;
        fetchAction('deleteSlave', deleteInfo);
        this.handleShowDelModal(false);
    }

    handleChangeMainCellType = (values: any) => {
        const { key = '1', label } = values;
        this.setState({
            showImg: {
                src: Number(key),
                title: label,
            },
        });
    }

    render() {
        const {
            vice_cabinet_list,
            delVisible,
            mainCellVisbile,
            showImg,
        } = this.state;

        const {
            detailInfo,
            slaveTypeList,
            forms: { getFieldDecorator },
            hardwareVersion,
        }: any = this.props;

        const { cellInfo } = detailInfo;

        const is_version = (hardwareVersion === '5.0'
            || hardwareVersion === '6.0'
            || hardwareVersion === '7.0') ? 1 : 0;

        const is_Low_version = (detailInfo.hwareVersion === '1.0'
            || detailInfo.hwareVersion === '2.0'
            || detailInfo.hwareVersion === '2.7'
            || detailInfo.hwareVersion === '3.0'
            || detailInfo.hwareVersion === '4.0'
            || detailInfo.hwareVersion === '4.1') ? 0 : 1;

        const cardTitle = detailInfo.id && is_Low_version === 1
            ? `柜体布局（副柜总数${detailInfo.cellInfo?.length || 0}）` : '柜体布局';

        const is_add = detailInfo.id ? vice_cabinet_list.length - (cellInfo?.length || 0) : 0;

        const ADDBUTTON = detailInfo.id && is_Low_version === 1
            ? (
                <Button
                    type="primary"
                    size="small"
                    disabled={Boolean(is_add)}
                    onClick={this.handleAddVice}
                >
                    增加副柜
                </Button>
            ) : null;


        return (
            <>
                <Card
                    bordered={false}
                    title={cardTitle}
                    extra={ADDBUTTON}
                >
                    <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                        {!detailInfo.id && is_version === 1 && (
                            <Col md={10} sm={24} style={{ display: 'flex' }}>
                                <Form.Item label="主柜格口类型" style={{ flex: 1 }}>
                                    {getFieldDecorator('mainType', {
                                        initialValue: { key: '1' },
                                        rules: [{ required: true, message: '请选择主柜格口类型' }],
                                    })(
                                        <Select
                                            showSearch
                                            labelInValue
                                            placeholder="请选择"
                                            onChange={this.handleChangeMainCellType}
                                            filterOption={(input: any, option: any) => option.props.children
                                                .toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        >
                                            {slaveTypeList.map((item: any) => (
                                                <Option value={item.key} key={item.key}>{item.value}</Option>
                                            ))}
                                        </Select>,
                                    )}
                                </Form.Item>
                                <Button
                                    type="link"
                                    onClick={() => this.setState({ mainCellVisbile: true })}
                                >
                                    示例图
                                </Button>
                            </Col>
                        )}
                        {(is_Low_version === 0 || !detailInfo.id) && (
                            <Col md={8} sm={24} style={{ display: 'flex', alignItems: 'center' }}>
                                <Form.Item label="副柜布局" colon={false} style={{ width: 170 }} />
                                {getFieldDecorator('layout_left', {
                                    initialValue: (detailInfo.layout && Number(detailInfo.layout.split('-')[0])) || 0,
                                    rules: [{ required: true, message: '请选择副柜布局' }],
                                })(
                                    <Select
                                        placeholder="请选择"
                                        disabled={Boolean(detailInfo.id)}
                                        onSelect={(e: any) => this.handlechangeLayout(e, 1)}
                                    >
                                        {[...new Array(41)].map((item: any, index: number) => (
                                            <Option value={index} key={index}>左侧-{index}组</Option>
                                        ))}
                                    </Select>,
                                )}
                                {getFieldDecorator('layout_right', {
                                    initialValue: (detailInfo.layout && Number(detailInfo.layout.split('-')[1])) || 0,
                                    rules: [{ required: true, message: '请选择副柜布局' }],
                                })(
                                    <Select
                                        placeholder="请选择"
                                        className="marginL16"
                                        disabled={Boolean(detailInfo.id)}
                                        onSelect={(e: any) => this.handlechangeLayout(e, 2)}
                                    >
                                        {[...new Array(41)].map((item: any, index: number) => (
                                            <Option value={index} key={index}>右侧-{index}组</Option>
                                        ))}
                                    </Select>,
                                )}
                            </Col>
                        )}
                    </Row>
                    <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                        {vice_cabinet_list.map((item: any, index: number) => (
                            <Col md={12} sm={24} key={item.slaveCode} style={{ display: 'flex' }}>
                                <Form.Item label={`副柜${item.slaveCode}`} colon={false} style={{ flex: 1 }}>
                                    {getFieldDecorator(`vice[${index}]`, {
                                        initialValue: item.slaveType.toString(),
                                        rules: [{ required: true, message: `请选择副柜${item.slaveCode}` }],
                                    })(
                                        <Select
                                            allowClear
                                            showSearch
                                            placeholder="请选择"
                                            disabled={Boolean(!item.isAdd)}
                                            filterOption={(input: any, option: any) => (
                                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            )}
                                        >
                                            {slaveTypeList.map((type: any) => (
                                                <Option value={type.key} key={type.key}>{type.value}</Option>
                                            ))}
                                        </Select>,
                                    )}
                                </Form.Item>
                                {!item.isAdd && (
                                    <span className="marginL8" style={{ display: 'inline-block', lineHeight: '32px' }}>
                                        共{item.cellCount}格口
                                    </span>
                                )}
                                {index === vice_cabinet_list.length - 1
                                    && is_Low_version === 1
                                    && detailInfo.id
                                    && (
                                        <Button
                                            type="link"
                                            style={{ color: '#ec4244' }}
                                            onClick={() => this.handleShowDelModal(true, item)}
                                        >删除
                                        </Button>
                                    )}
                            </Col>
                        ))}
                    </Row>
                    <Modal
                        visible={delVisible}
                        onOk={this.handleDelSubmit}
                        onCancel={() => this.handleShowDelModal(false)}
                    >
                        <p>确定删除当前副柜吗？</p>
                    </Modal>
                </Card>
                <Modal
                    title={showImg.title}
                    width={1000}
                    visible={mainCellVisbile}
                    footer={false}
                    onCancel={() => this.setState({ mainCellVisbile: false })}
                >
                    <div style={{ textAlign: 'center', height: '68vh', overflow: 'auto' }}>
                        <img src={CabImages[showImg.src]} alt="" />
                    </div>
                </Modal>
            </>
        );
    }
}

export default CabinetInfoElem;
